import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket=null;

    public TcpEchoClient(String serverIP,int serverPort) throws IOException {
        socket=new Socket(serverIP,serverPort);
    }

    public void start(){
        System.out.println("客户端已启动");

        try(InputStream inputStream=socket.getInputStream();
            OutputStream outputStream=socket.getOutputStream()) {
            Scanner scanner=new Scanner(inputStream);
            Scanner sc=new Scanner(System.in);
            PrintWriter printWriter=new PrintWriter(outputStream);

            while(true){
                //1.从控制台读取数据
                System.out.print("->");
                String request=sc.next();

                //2.把请求发给服务器
                printWriter.println(request);
                printWriter.flush();

                //3.服务器读响应
                if(!scanner.hasNext()){
                    break;
                }
                String response=scanner.next();
                //打印日志
                System.out.println(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient =new TcpEchoClient("127.0.0.1",9090);
        tcpEchoClient.start();

    }
}
